package controller

import (
	"fmt"
	"go_jwt/initializer"
	"go_jwt/model"
	"net/http"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
	"golang.org/x/crypto/bcrypt"
)

type Params struct {
	Email    string
	Password string
}

// 注册接口
func SignUp(c *gin.Context) {

	// 获取请求参数 email password 然后返回结果

	var body Params

	if c.Bind(&body) != nil {

		c.JSON(http.StatusBadRequest, gin.H{
			"error": "Failed to read body ",
		})

		return
	}

	//密码加密

	hash, err := bcrypt.GenerateFromPassword([]byte(body.Password), 10)

	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "Failed to hash password ",
		})

		return
	}

	// 创建用户并存入数据库

	user := model.User{Email: body.Email, Password: string(hash)}

	result := initializer.DB.Create(&user)

	fmt.Printf("user = %v", user)

	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "Failed to save user ",
		})

		return
	}

	//响应

	c.JSON(http.StatusOK, gin.H{})

}

// 登录接口

func Login(c *gin.Context) {

	var body Params

	if c.Bind(&body) != nil {

		c.JSON(http.StatusBadRequest, gin.H{
			"error": "Failed to read body ",
		})

		return
	}

	var user model.User
	initializer.DB.First(&user, "email = ?", body.Email)

	fmt.Printf("user = %v", user)

	if user.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "Invalid user ID",
		})
		return
	}

	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(body.Password))

	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "Invalid email or password ",
		})
		return
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"sub": user.ID,
		"exp": time.Now().Add(time.Hour * 24 * 30).Unix(),
	})

	tokenStr, err := token.SignedString([]byte(os.Getenv("SECERET")))

	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "filed to create token ",
		})
		return
	}

	c.SetSameSite(http.SameSiteLaxMode)
	c.SetCookie("Authorization", tokenStr, 3600*24*30, "", "", false, true)

	c.JSON(http.StatusOK, gin.H{
		"message": "登录成功",
	})

}

// 验证接口
func Validate(c *gin.Context) {

	c.JSON(http.StatusOK, gin.H{
		"message": " I m logined ",
	})

}
